from rest_framework import serializers
from .models import CameraBrand, Camera, CameraImage


class CameraBrandSerializer(serializers.ModelSerializer):
    class Meta:
        model = CameraBrand
        fields = ['id', 'name', 'logo_url', 'description']


#相机卡片的序列化器
from rest_framework import serializers
from .models import Camera
class CameraImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = CameraImage
        fields = ['image_url']
class CameraListSerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField()
    image = serializers.URLField(source='image_url')
    # images = CameraImageSerializer(many=True, read_only=True)

    price = serializers.SerializerMethodField()
    originalPrice = serializers.SerializerMethodField()
    rating = serializers.SerializerMethodField()
    reviews = serializers.SerializerMethodField()
    pixels = serializers.CharField(source='resolution')
    features = serializers.SerializerMethodField()
    isNew = serializers.SerializerMethodField()
    isHot = serializers.SerializerMethodField()

    class Meta:
        model = Camera
        fields = [
            'id', 'name', 'model', 'image', 'price', 'originalPrice',
            'rating', 'reviews', 'video', 'pixels', 'features',
            'isNew', 'isHot'
        ]

    def get_name(self, obj):
        return f"{obj.brand} {obj.model}"

    def get_price(self, obj):
        # 尝试从 reference_price 中提取数字，如“约16999元” → 16999
        import re
        match = re.search(r'\d+', obj.reference_price)
        return int(match.group()) if match else 0

    def get_originalPrice(self, obj):
        return None  # 暂无原价字段，可留空

    def get_rating(self, obj):
        return 4.5  # 示例：后期可接入 CameraRating 模型评分

    def get_reviews(self, obj):
        return 20  # 示例：可接入评论数

    def get_features(self, obj):
        return [tag.name for tag in obj.tags.all()]

    def get_isNew(self, obj):
        return '2023' in obj.release_date or '2024' in obj.release_date

    def get_isHot(self, obj):
        return self.get_rating(obj) >= 4.5





class CameraDetailSerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField()
    images = CameraImageSerializer(many=True, read_only=True)

    class Meta:
        model = Camera
        fields = [
            'id', 'name', 'model', 'type', 'video',
            'images', 'reference_price', 'resolution',
            'release_date', 'format','weight','bluetooth'
            ,'frame_rate','shutter_speed','image_sensor_type','monitor_size','shutter_speed'
        ]

    def get_name(self, obj):
        return f"{obj.brand} {obj.model}"
